const Logger = require('../../utils/logUtil.js');
// 邀请好友砍价页面逻辑 (优化后的代码)
Page({
	data: {
		userInfo: {
			avatar: '',
			nickName: ''
		},
		price: '', //单价
		quantity: '', //数量
		progress: '', //砍价进度
		reducedAmount: '', //已砍金额
		totalAmount: '', //总共需要砍
		pay_amount: '', //直接购买
		image_url: '', //产品图
		options: {},
    participantId: '', //砍价参与id
    productTitle:'',
		countdown: {},
		timer: null,
		helperRankList: [
			{
                "nickName": "微信用户1",
                "avatar": "https://yt3.ggpht.com/yti/ANjgQV8NVKopWke4nqIYQlPC6t__I2FofHAP0Ct7vYbr_PA1wg=s88-c-k-c0x00ffffff-no-rj",
                "helpedPrice": "2.5",
                "helpTime":"2分钟前"
			},
			{
                "nickName": "微信用户1",
                "avatar": "https://yt3.ggpht.com/yti/ANjgQV8NVKopWke4nqIYQlPC6t__I2FofHAP0Ct7vYbr_PA1wg=s88-c-k-c0x00ffffff-no-rj",
                "helpedPrice": "2.5",
                "helpTime":"2分钟前"
            }
    ],
    noticeText:'',
    allowBargainPrice:null,
    shareTitle:'快来帮忙砍一刀，一起抢免费洗鞋名额',
    shareDesc:'快来帮忙砍一刀，一起抢免费洗鞋名额',
    shareImg:'https://7072-prod-3gjcorog35addaa7-1348173015.tcb.qcloud.la/bargain/ad_pop-up_part_image.png?sign=6be61c1e043ca1ee3dc9a0ad4ad155fd&t=1745027558',
	},

	onLoad: function (options) {
		const userInfo = wx.getStorageSync('userInfo');
		const nickName = userInfo?.nickName || '匿名用户';
		const avatar = userInfo?.avatarUrl || 'https://7072-prod-3gjcorog35addaa7-1348173015.tcb.qcloud.la/bargain/avatar.png?sign=aece51af695d8cfe527779bfecdcc901&t=1742573112';
		
		const param = JSON.parse(decodeURIComponent(options.param));
		console.log(param);
		this.setData({
			options: param,
			userInfo: {
				nickName,
				avatar
			}
		});
	},

	onShow: function () {
		// 开启分享功能
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline'], // 显示分享按钮
		});
		this.onGetDetailInfo(); // 加载页面数据
	},

	/**
	 * 分享
	 */
	onShareAppMessage: function (res) {
		console.log(res.from);
		if (res.from === 'button') {
			return {
				title: this.data.shareTitle,
				desc: this.data.shareDesc,
				imageUrl: this.data.shareImg,
				path: `/pages/invited1/index?participantId=${this.data.participantId}`,
				success: function (res) {
					// 分享成功的处理逻辑
				},
				fail: function (res) {
					// 分享失败的处理逻辑
				},
			};
		}
	},

	onGetDetailInfo: function () {
		wx.showLoading({
			title: '加载中',
		});
    let createBargainRequest = {
      productId: this.data.options.productId,
      userId: wx.getStorageSync('openId'),
      quantity: this.data.options.count,
    };
		// 获取砍价详情
		wx.cloud.callFunction({
			name: 'xiaoBangCommonFunction',
			data: {
        createBargainRequest:createBargainRequest
      },
			success: (res) => {
				console.log("res", res)
				if(res.code !== 200) {
					wx.showToast({
					  title: '接口异常',
					  icon: 'error'
					});
					Logger.error('onGetDetailInfo.createBargainRequest fail', JSON.stringify(res));
				}
				this.setData({
					participantId: res.result.data.participantId,
					totalAmount: res.result.data.totalAmount,
					pay_amount: res.result.data?.pay_amount,
				});
				wx.hideLoading();
				this.getDetail();
			},
			fail: (err) => {
				console.error('[云函数] [createBargain] 调用失败', err);
				Logger.error('onGetDetailInfo.createBargainRequest fail', JSON.stringify(err));
			},
		});
	},

	// 获取砍价详情
	getDetail: function () {
		wx.showLoading({
			title: '加载中',
		});
		let getBargainDetailRequest = {
			participantId: this.data.participantId,
		}
		wx.cloud.callFunction({
			name: 'xiaoBangCommonFunction',
			data: {
				getBargainDetailRequest:getBargainDetailRequest
			},
			success: (res) => {
        console.log(">>>获取砍价详情res",JSON.stringify(res));
				let promesison = parseFloat(res.result.data.totalAmount) - parseFloat(res.result.data.reducedAmount);
				let progress = 1 - promesison / parseFloat(res.result.data.totalAmount);
				let percentage = (progress * 100).toFixed(2) + '%';
				console.log('> timeLeft: ', res.result.data.timeLeft);

				this.setData({
          participantId: res.result.data.participantId,
          productId: res.result.data.productId,
          productTitle: res.result.data.productTitle,
					price: res.result.data.price,
					quantity: res.result.data.quantity,
					reducedAmount: res.result.data.reducedAmount,
					image_url: res.result.data.imageUrl,
					totalAmount: res.result.data.totalAmount,
					pay_amount: res.result.data.payAmount,
					progress: percentage,
					timeLeft: res.result.data.timeLeft,
          helperRankList: res.result.data.helperRankList,
          noticeText:res.result.data.noticeText,
          allowBargainPrice:res.result.data.allowBargainAmount,
          shareTitle:res.result.data.shareTitle,
          shareDesc:res.result.data.shareDesc,
          shareImg:res.result.data.shareImg
				});
				this.startCountdown()
        wx.hideLoading();
        const notAllowContinueBargain = (this.data.reducedAmount && this.data.allowBargainPrice) && (parseFloat(this.data.reducedAmount) * 10 - this.data.allowBargainPrice >= 0);
        if (notAllowContinueBargain) {
          wx.showToast({
						title: "这单只能砍这么多了，再砍👀商家要吐血了，去下单吧~",
						icon: 'none',
						duration: 4000
					});
        }
        else if(!!this.data.noticeText) {
					wx.showToast({
						title: this.data.noticeText,
						icon: 'none',
						duration: 4000
					});
				}
			},
			fail: (err) => {
				console.error('[云函数] [getBarginInfo] 调用失败', err);
				Logger.error('getDetail.getBargainDetailRequest fail', JSON.stringify(err));
			},
		});
	},
	timer: null, // 将 timer 放在 this 上，而不是 data 中
	convertSeconds(seconds) {
		const hours = Math.floor(seconds / 3600);
		const minutes = Math.floor((seconds % 3600) / 60);
		const remainingSeconds = seconds % 60;
		return { hours, minutes, seconds: remainingSeconds };
	},
	startCountdown() {
		// 清除之前的定时器
		if (this.timer) {
			clearTimeout(this.timer);
		}

		// 每秒更新一次倒计时
		const tick = () => {
			let { timeLeft } = this.data;

			if (timeLeft <= 0) {
				clearTimeout(this.timer); // 倒计时结束，清除定时器
				this.setData({ timeLeft: 0, countdown: this.convertSeconds(0) }); // 重置为 0
				wx.showToast({ title: '倒计时结束', icon: 'none' });
				return;
			}

			timeLeft -= 1; // 每秒减少 1 秒
			this.setData({
				timeLeft,
				countdown: this.convertSeconds(timeLeft) // 更新倒计时显示
			});

			// 递归调用
			this.timer = setTimeout(tick, 1000); // 每 1000ms 更新一次
		};

		tick(); // 启动倒计时
	},
	// 直接购买
	directPurchasing: function () {
		const param = {
			image_url: this.data.image_url,
			productId: this.data.options.productId,
			count: this.data.quantity, //购买商品的数量
			fromPage: "bargin", //order:点击首页的下单进来的；bargin：点击砍价页的下单进来的
			discount_amount: this.data.pay_amount, //如果是从砍价页进来的，砍价金额传给后端
      participantId: this.data.participantId, //如果是从砍价页进来的，输入生成的砍价id,
      schoolCode: this.data.options.schoolCode
		}; // 要传递的参数
		console.log(param);
		wx.navigateTo({
			url: '/pages/placeAnOrder2/placeAnOrder2?param=' + encodeURIComponent(JSON.stringify(param))
		});
	},
	onPullDownRefresh() {
		this.getDetail();
		wx.stopPullDownRefresh();
	}
});